package com.blb.socket.demo2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * UDP服务器
 */
public class UDPServer {

    public static final int PORT = 8888;

    public void start(){
        System.out.println("服务器启动");
        //创建服务器端的UDPSocket
        try (DatagramSocket server = new DatagramSocket(PORT)){
            //接收数据报
            while(true){
                //创建数据包，接收数据
                byte[] buf = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buf,0,buf.length);
                server.receive(packet);
                System.out.println(packet.getAddress() +"说：" +
                        new String(packet.getData(),packet.getOffset(),packet.getLength()));
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new UDPServer().start();
    }
}
